<script setup>
import { ref } from 'vue'
import { _saveClothingStyle } from '@/api/clothingStyle'
import { _uploadFile } from '@/api/file'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 表单数据
const styleForm = ref({
  name: '',  // 修改：styleName -> name
  genderLimit: null,  // 修改：gender -> genderLimit (Byte类型)
  image: '',  // 新增图片字段
  sizes: []
})

// 尺码信息表单（只保留size和description）
const sizeForm = ref({
  size: '',
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入款式名称', trigger: 'blur' }
  ],
  genderLimit: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

const formRef = ref(null)

// 添加尺码
const addSize = () => {
  if (!sizeForm.value.size) {
    ElMessage.warning('请填写尺码')
    return
  }
  styleForm.value.sizes.push({ ...sizeForm.value })
  sizeForm.value = {
    size: '',
    description: ''
  }
}

// 删除尺码
const removeSize = (index) => {
  styleForm.value.sizes.splice(index, 1)
}

// 图片上传前的校验
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义上传方法
const handleUpload = async (options) => {
  const { file } = options
  
  try {
    const res = await _uploadFile(file)
    if (res.code === 200) {
      // 假设后端返回的数据格式为 { url: '图片地址' }
      styleForm.value.image = res.data.url || res.data.data || res.data
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(res.message || '图片上传失败')
    }
  } catch (error) {
    ElMessage.error('图片上传失败')
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      _saveClothingStyle(styleForm.value).then(res => {
        if (res.code === 200) {
          ElMessage.success('添加成功')
          resetForm()
        } else {
          ElMessage.error(res.message || '添加失败')
        }
      })
    }
  })
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
  styleForm.value.sizes = []
  styleForm.value.image = ''  // 清空图片
  sizeForm.value = {
    size: '',
    description: ''
  }
}

// 返回列表
const goBack = () => {
  router.push('/clothingStyle/list')
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>款式添加</span>
      </div>
    </template>

    <el-form
        ref="formRef"
        :model="styleForm"
        :rules="rules"
        label-width="100px"
        style="max-width: 800px"
    >
      <el-form-item label="款式名称" prop="name">
        <el-input v-model="styleForm.name" placeholder="请输入款式名称" />
      </el-form-item>
      
      <el-form-item label="性别" prop="genderLimit">
        <el-select v-model="styleForm.genderLimit" placeholder="请选择性别">
          <el-option label="女" :value="0" />
          <el-option label="男" :value="1" />
          <el-option label="通用" :value="2" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="款式图片">
        <el-upload
            class="avatar-uploader"
            :action="''"
            :show-file-list="false"
            :http-request="handleUpload"
            :before-upload="beforeUpload"
        >
          <img v-if="styleForm.image" :src="styleForm.image" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div style="color: #999; font-size: 12px; margin-top: 5px;">支持 jpg/png 格式，大小不超过 2MB</div>
      </el-form-item>

      <!-- 尺码信息 -->
      <el-divider>尺码信息</el-divider>
      
      <el-form :inline="true" :model="sizeForm" size="small">
        <el-form-item label="尺码" style="width: 200px">
          <el-input v-model="sizeForm.size" placeholder="如：M, 170/88A" style="width: 150px" />
        </el-form-item>
        <el-form-item label="尺码说明" style="width: 100%">
          <el-input 
            v-model="sizeForm.description" 
            placeholder="如：适合身高170-175cm" 
            style="width: 100%" 
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Plus" size="small" @click="addSize">添加尺码</el-button>
        </el-form-item>
      </el-form>

      <!-- 已添加的尺码列表 -->
      <el-table
          v-if="styleForm.sizes.length > 0"
          :data="styleForm.sizes"
          style="width: 100%; margin-top: 20px"
          border
      >
        <el-table-column prop="size" label="尺码" width="120" />
        <el-table-column prop="description" label="尺码说明" show-overflow-tooltip />
        <el-table-column label="操作" width="100" align="center">
          <template #default="{ $index }">
            <el-button type="danger" :icon="Delete" size="small" @click="removeSize($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 表单按钮 -->
      <el-form-item style="margin-top: 30px">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

// 图片上传样式
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style>
